package com.hkfn.rfb.common.utils;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInstaller;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class InstallUtil {

    private static String TAG = "InstallUtil";

    public static void install(Context context, String filePath) {
        if (!StringUtils.isEmpty(filePath)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                install26(context, filePath);
            }else {
                FileUtil.install(filePath);
            }
        }
    }

    @RequiresApi(api = 26)
    public static void install26(Context context, String filePath) {
        try {
            File file = new File(filePath);
            if (file.exists() && file.isFile()) {
                PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
                PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL);
                params.setSize(file.length());
                int sessionId = packageInstaller.createSession(params);
                PackageInstaller.Session session = packageInstaller.openSession(sessionId);
                InputStream in = new FileInputStream(file);
                OutputStream out = session.openWrite("CocosDemo", 0, file.length());
                byte[] buffer = new byte[65536];
                int c;
                while ((c = in.read(buffer)) != -1) {
                    out.write(buffer, 0, c);
                }
                session.fsync(out);
                in.close();
                out.close();
                session.commit(PendingIntent.getBroadcast(context, sessionId,
                        new Intent("android.intent.action.PACKAGE_ADDED"), 0).getIntentSender());
            }
        } catch (Exception e) {
            Log.e(TAG,"安装失败:"+e.getMessage());
            e.printStackTrace();
        }
    }
}